<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>课程管理</el-breadcrumb-item>
		<el-breadcrumb-item>订单管理</el-breadcrumb-item>
	</el-breadcrumb>
	<div>
		<el-form :inline="true" :model="formInline" class="demo-form-inline">
			<el-form-item label="用户名:">
				<el-input v-model="formInline['user.nickname']" placeholder="请输入用户名" clearable :suffix-icon="Search"
					@clear="handleClear" />
			</el-form-item>
			<el-form-item label="课程名称:">
				<el-input v-model="formInline['course.courseName']" placeholder="请输入课程名称" clearable
					:suffix-icon="Search" @clear="handleClear" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit">搜索</el-button>
				<el-button type="danger" @click="batchDelete">批量删除</el-button>
			</el-form-item>
		</el-form>
	</div>
	<el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
		<el-table-column type="selection" fixed prop="id" label="ID" width="60" />
		<el-table-column prop="id" label="id" width="60" />
		<el-table-column prop="user.nickname" label="用户名" width="120" />
		<el-table-column prop="course.courseName" label="课程名" width="860" />
		<el-table-column prop="buyTime" label="下单时间" width="180" />
		<el-table-column fixed="right" label="操作" min-width="150">
			<template #default="scope">
				<el-button type="danger" size="small" @click="remove(scope.row.id)">
					删除
				</el-button>
			</template>
		</el-table-column>
	</el-table>
	<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
		:size="size" :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<script setup>
	import axios from 'axios'
	import {
		onMounted,
		reactive,
		ref
	} from 'vue'
	import {
		Search
	} from '@element-plus/icons-vue'
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";

	const flname = ref('')
	const currentId = ref(0)

	const dialogFormVisible = ref(false)
	const dialogFormVisible1 = ref(false)

	const remove = (id) => {
		ElMessageBox.confirm(
				'请确认是否删除?',
				'Warning', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			).then(() => {
				axios.delete(`http://localhost:8080/courseOrder/${id}`)
					.then(response => {
						if (response.data.code == 200) {
							ElMessage({
								type: 'success',
								message: '删除成功',
							});
						} else {
							ElMessage({
								type: 'error',
								message: '删除失败，状态码：' + response.status,
							});
						}
					})
					.catch(error => {
						ElMessage({
							type: 'error',
							message: '请求失败，请稍后再试',
						});
					})
					.finally(() => {
						query();
					});
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				});
			});
	}

	const detailArea = ref('')
	const selectedAddresses = ref([])
	const handleChangeAddress = (d) => {}

	// 修改：使用与后端匹配的参数名
	const formInline = reactive({
		'user.nickname': "",
		'course.courseName': "",
		pageSize: 10,
		pageNum: 1,
	})

	const courseClassify = {
		id: 0,
		courseClassifyName: ''
	};

	let tableData = ref([])
	const selectedRows = ref([]);
	const tableRef = ref(null);
	const total = ref(0)
	const currentPage = ref(1)
	const pageSize = ref(10)
	const size = ref('small')
	const background = ref(true)

	// 基础查询函数
	const query = () => {
		axios.get(
				`http://localhost:8080/courseOrder/page?pageSize=${pageSize.value}&pageNum=${currentPage.value}`
			)
			.then(response => {
				tableData.value = response.data.data.list
				total.value = response.data.data.total
			})
			.catch(error => {
				console.log(error);
			});
	}

	// 修改：使用正确的参数名进行搜索
	const onSubmit = () => {
		currentPage.value = 1; // 重置为第一页
		axios.get(
				`http://localhost:8080/courseOrder/page?pageSize=${formInline.pageSize}&pageNum=${formInline.pageNum}&user.nickname=${formInline['user.nickname']}&course.courseName=${formInline['course.courseName']}`
			)
			.then(response => {
				tableData.value = response.data.data.list
				total.value = response.data.data.total
			})
			.catch(error => {
				console.log(error);
			});
	}

	const add = () => {
		axios.post('http://localhost:8080/courseOrder', {
				id: "",
				courseClassifyName: flname.value
			})
			.then(response => {
				ElMessage({
					type: 'success',
					message: '新增成功',
				});
			})
			.catch(error => {
				ElMessage({
					type: 'error',
					message: '新增失败',
				});
			})
			.finally(() => {
				query();
				dialogFormVisible.value = false;
			});
	}

	const change = () => {
		const requestData = {
			id: currentId.value,
			courseClassifyName: flname.value
		};

		axios.put('http://localhost:8080/courseOrder', requestData, {
				headers: {
					'Content-Type': 'application/json'
				}
			})
			.then(response => {
				if (response.data.code === 200) {
					ElMessage({
						type: 'success',
						message: '修改成功',
					});
				} else {
					ElMessage({
						type: 'error',
						message: '修改失败：' + response.data.message,
					});
				}
			})
			.catch(error => {
				ElMessage({
					type: 'error',
					message: '请求失败，请稍后再试',
				});
			})
			.finally(() => {
				query();
				dialogFormVisible1.value = false;
			});
	}

	onMounted(() => {
		query()
	})

	const handleClear = () => {
		formInline['user.nickname'] = "";
		formInline['course.courseName'] = "";
		query();
	}

	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
	}

	const handleCurrentChange = (val) => {
		currentPage.value = val;
		query();
	}

	const handleSelectionChange = (val) => {
		selectedRows.value = val;
	}

	const batchDelete = async () => {
		if (selectedRows.value.length === 0) {
			ElMessageBox.alert('至少选择一条数据才能进行删除', {
				confirmButtonText: 'OK',
				callback: (action) => {
					ElMessage({
						type: 'info',
						message: `action: ${action}`,
					})
				},
			})
			return;
		}

		const ids = selectedRows.value.map(row => row.id).join(',');
		try {
			await axios.delete(`http://localhost:8080/courseOrder?ids=${ids}`);
			ElMessage({
				type: 'success',
				message: '删除成功',
			});
			query();
		} catch (error) {
			ElMessage({
				type: 'error',
				message: '删除失败',
			});
			console.error(error);
		}
	};

	const bianji = (row) => {
		dialogFormVisible1.value = true;
		flname.value = row.courseClassifyName;
		currentId.value = row.id;
	}
</script>

<style>
	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	el-table-column {
		max-height: 150px;
	}

	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
		border: 1px;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-breadcrumb {
		border-bottom: 1px solid #EEEEEE;
		padding-bottom: 15px;
	}
</style>